package com.example.burnafterreading.controller;

import com.example.burnafterreading.model.Message;
import com.example.burnafterreading.service.MessageService;
import com.example.burnafterreading.dto.MessageRequest;
import com.example.burnafterreading.dto.PasswordVerificationRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Base64;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
@RequestMapping(value = "/api/messages", produces = MediaType.APPLICATION_JSON_VALUE)
@CrossOrigin(origins = "*")
public class MessageController {

    private static final Logger logger = LoggerFactory.getLogger(MessageController.class);

    @Autowired
    private MessageService messageService;

    @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> createMessage(@RequestBody MessageRequest request) {
        try {
            logger.info("Creating message with title: {}", request.getTitle());
            Message message = messageService.createMessage(request);
            return ResponseEntity.ok(message);
        } catch (Exception e) {
            logger.error("Error creating message: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().body(new ErrorResponse("创建消息失败：" + e.getMessage()));
        }
    }

    @GetMapping("/{accessKey}/protected")
    public ResponseEntity<?> isPasswordProtected(@PathVariable String accessKey) {
        try {
            boolean isProtected = messageService.isPasswordProtected(accessKey);
            Map<String, Boolean> response = new HashMap<>();
            response.put("protected", isProtected);
            return ResponseEntity.ok(response);
        } catch (RuntimeException e) {
            logger.error("Error checking if message is password protected: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().body(new ErrorResponse(e.getMessage()));
        }
    }

    @PostMapping("/{accessKey}/verify")
    public ResponseEntity<?> verifyPassword(
            @PathVariable String accessKey,
            @RequestBody PasswordVerificationRequest request) {
        try {
            boolean isValid = messageService.checkPassword(accessKey, request.getPassword());
            Map<String, Boolean> response = new HashMap<>();
            response.put("valid", isValid);
            return ResponseEntity.ok(response);
        } catch (RuntimeException e) {
            logger.error("Error verifying password: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().body(new ErrorResponse(e.getMessage()));
        }
    }

    @GetMapping("/{accessKey}")
    public ResponseEntity<?> readMessage(
            @PathVariable String accessKey,
            @RequestParam(required = false) String password) {
        try {
            Message message = messageService.readMessage(accessKey, password);
            // 如果消息包含图片，将其转换为Base64
            if (message.getImage() != null) {
                String base64Image = Base64.getEncoder().encodeToString(message.getImage());
                message.setImage(null); // 清除字节数组
                // 创建包含Base64图片的响应
                return ResponseEntity.ok(new MessageResponse(
                        message.getContent(),
                        "data:" + message.getImageType() + ";base64," + base64Image,
                        message.getAccessKey(),
                        message.isRead(),
                        message.getCreatedAt(),
                        message.getTitle()
                ));
            }
            return ResponseEntity.ok(message);
        } catch (Exception e) {
            logger.error("Error reading message: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().body(new ErrorResponse(e.getMessage()));
        }
    }
}

class ErrorResponse {
    private String message;

    public ErrorResponse(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

class MessageResponse {
    private String content;
    private String image;
    private String accessKey;
    private boolean read;
    private LocalDateTime createdAt;

    private String title;

    public MessageResponse(String content, String image, String accessKey, boolean read, LocalDateTime createdAt, String title) {
        this.content = content;
        this.image = image;
        this.accessKey = accessKey;
        this.read = read;
        this.createdAt = createdAt;
        this.title = title;
    }

    // Getters and setters
    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getAccessKey() {
        return accessKey;
    }

    public void setAccessKey(String accessKey) {
        this.accessKey = accessKey;
    }

    public boolean isRead() {
        return read;
    }

    public void setRead(boolean read) {
        this.read = read;
    }

    public LocalDateTime getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(LocalDateTime createdAt) {
        this.createdAt = createdAt;
    }

    public String getTitle() {
        return title;
    }
}
